<template>
  <a-modal :visible="visible" title="设置列表列" @ok="handleOk" @cancel="cancel">
    <a-form :labelCol="{ span: 7 }" :wrapperCol="{ span: 16 }">
      <a-form-item label="添加字段" v-bind="validateInfos.dataIndex">
        <a-input placeholder="请输入字段" v-model:value="modelRef.dataIndex"></a-input>
      </a-form-item>
      <a-form-item label="添加标题" v-bind="validateInfos.title">
        <a-input placeholder="请输入标题" v-model:value="modelRef.title" />
      </a-form-item>
      <a-form-item label="设定宽度" v-bind="validateInfos.width">
        <a-input
          style="width: 315px"
          v-model:value="modelRef.width"
          placeholder="请输入宽度，宽度单位默认为px"
        />
      </a-form-item>
      <a-form-item label="超出一行省略" v-bind="validateInfos.ellipsis">
        <a-radio-group v-model:value="modelRef.ellipsis">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { defineComponent, reactive, toRaw, toRefs, watch } from 'vue';
import { useForm } from '@ant-design-vue/use';
import _ from 'lodash-es';

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({
        dataIndex: '',
        title: '',
        width: '',
        ellipsis: 0,
      }),
    },
  },
  emits: ['edit-column', 'add-column', 'update:visible'],
  setup(props, { emit }) {
    const { form } = toRefs(props);
    console.log(form);
    const state = reactive({
      modelRef: _.cloneDeep(form.value),
      rulesRef: {
        dataIndex: [
          {
            required: true,
            message: '请输入字段',
          },
        ],
        title: [
          {
            required: true,
            message: '请输入标题',
          },
        ],
      },
    });
    watch(
      form,
      key => {
        state.modelRef = key;
      },
      { deep: true },
    );
    const confirmForm = () => {
      let { dataIndex, title, width, ellipsis, index } = _.cloneDeep(toRaw(state.modelRef));
      if (width && !isNaN(width)) {
        width += 'px';
      }
      index === undefined
        ? emit('add-column', { dataIndex, title, width, ellipsis })
        : emit('edit-column', { dataIndex, title, width, ellipsis, index });
    };
    const { resetFields, validate, validateInfos } = useForm(state.modelRef, state.rulesRef);
    const handleOk = () => {
      validate()
        .then(() => {
          confirmForm();
          cancel();
        })
        .catch(err => {
          console.log('error', err);
        });
    };
    const cancel = () => {
      emit('update:visible', false);
      state.modelRef.index = undefined;
      resetFields();
    };

    return {
      ...toRefs(state),
      cancel,
      validateInfos,
      validate,
      handleOk,
    };
  },
});
</script>
<style lang="less">
// TODO
</style>
